﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using System.Collections.Generic;
using AAEngine.Engine.Debug;
using AAEngine.Engine.Entities;

namespace AAEngine.Engine.Components
{
    /// <summary>
    /// Utility class to manage a group of entities marked with GroupManagerComponent.
    /// </summary>
    public class GroupManagerComponent : EntityComponent
    {
        private IList<GroupMemberComponent> _members = new List<GroupMemberComponent>();

        public static bool AutoCreateNamedGroups { get; set; }

        static GroupManagerComponent()
        {
            AutoCreateNamedGroups = true;
        }

        public static GroupManagerComponent GetGroupByName(string name)
        {
            var groupName = name;
            var gm = AAGame.LookupComponentByType(groupName, typeof(GroupManagerComponent)) as GroupManagerComponent;

            if (gm == null)
            {
                if (!AutoCreateNamedGroups)
                {
                    Logger.Warn(typeof(GroupManagerComponent), "GetGroupByName", "Tried to reference non-existent group '" + groupName + "'");
                }
                else
                {
                    var entity = Entity.New();
                    entity.Initialize(groupName);
                    gm = new GroupManagerComponent();
                    entity.AddComponent(gm, name);
                }
            }

            return gm;
        }

        public void AddMember(GroupMemberComponent member)
        {
            _members.Add(member);
        }

        public void RemoveMember(GroupMemberComponent member)
        {
            _members.Remove(member);
        }

        public IList<IEntity> EntityList
        {
            get
            {
                var entities = new List<IEntity>();
                foreach (var member in _members)
                {
                    entities.Add(member.Owner);
                }
                return entities;
            }
        }
    }
}
